import { getUser } from '@/api/personnal/person';
import personSelect from './personSelect';
export default {
	components: { personSelect },
	props: {
		value: { type: Boolean, default: false },
		dataId: [Number, String],
		dictData: { type: Object, default: () => {} }
	},
	data() {
		return {
			visible: this.value,
			btnLoading: false,
			checkedUsers: [],
			userDetail: {},
			isFirst: true,
			formData: {},
		};
	},
	computed: {
		userId() {
			return Number(this.$route.query.id);
		},
		addOrEdit() {
			return !this.dataId;
		},
		submitType() {
			return this.addOrEdit ? '添加' : '修改';
		},
		dialogTitle() {
			return `${this.submitType}${this.formName}`;
		},
		isDisabled() {
			return !!this.userId && this.addOrEdit;
		}
	},
	watch: {
		value(flag) {
			this.visible = flag;
		},
		visible(flag) {
			this.$emit('input', flag);
			this.isFirst = flag;
			if (!flag) return false;
			this.formData = {};
			this.checkedUsers = [];
			this.$nextTick(async () => {
				this.$refs['form'].clearValidate();
				if (!this.addOrEdit) {
					this.formData = await this.getDataDetail();
				} else if (!!this.userId) {
					this.$set(this.formData, 'userId', this.userId);
				}
			})
		},
		'formData.userId': {
			async handler(id) {
				console.log(id);
				if (!id) return false;
				this.userDetail = await this.getUserDetail(id);
				if (!!this.isFirst) {
					this.isFirst = false;
					this.checkedUsers = [this.userDetail];
				}
			}
		}
	},
	methods: {
		//获取人员详情
		async getUserDetail(id) {
			let result = await getUser(id);
			if (result.code === 200) {
				return Promise.resolve(result.data || {});
			}
		},

		//获取数据详情
		async getDataDetail() {
			let result = await this.detailFunction(this.dataId);
			if (result.code === 200) {
				return Promise.resolve(result.data || {});
			}
		},

		handleSubmitData() {
			this.$refs['form'].validate(valid => {
				if (!valid) return false;
				this.btnLoading = true;
				this.submitDataRequest();
			})
		},

		async submitDataRequest() {
			let params = this.formatRequestParams();
			let result = await this.callFunction(params);
			this.btnLoading = false;
			if (result.code === 200) {
				this.$modal.msgSuccess(`${this.submitType}成功`);
				this.visible = false;
				this.$emit('finish');
			}
		}
	}
};